<?php

function create_table_partition($table_name) { 
    $to_write_file = './sqls/'. $table_name. '.sql';
    if (!is_file($to_write_file)) { 
        echo "文件不存在: $to_write_file \n";
        exit;
    }

    $months = [
        '2020-05', '2020-06', 
        '2020-07', '2020-08', '2020-09', '2020-10', '2020-11', '2020-12',
        '2021-01', '2021-02', '2021-03', '2021-04', '2021-05', '2021-06', 
        '2021-07', '2021-08', '2021-09', '2021-10', '2021-11', '2021-12',
    ];

    $arr = [];
    foreach ($months as $month) { 
        list ($y, $m) = explode('-', $month);
        $arr[] = "CREATE TABLE ${table_name}_{$y}{$m}_01 PARTITION OF $table_name FOR VALUES FROM ('{$y}-{$m}-01') TO ('{$y}-{$m}-06');";
        $arr[] = "CREATE TABLE ${table_name}_{$y}{$m}_02 PARTITION OF $table_name FOR VALUES FROM ('{$y}-{$m}-06') TO ('{$y}-{$m}-11');";
        $arr[] = "CREATE TABLE ${table_name}_{$y}{$m}_03 PARTITION OF $table_name FOR VALUES FROM ('{$y}-{$m}-11') TO ('{$y}-{$m}-16');";
        $arr[] = "CREATE TABLE ${table_name}_{$y}{$m}_04 PARTITION OF $table_name FOR VALUES FROM ('{$y}-{$m}-16') TO ('{$y}-{$m}-21');";
        $arr[] = "CREATE TABLE ${table_name}_{$y}{$m}_05 PARTITION OF $table_name FOR VALUES FROM ('{$y}-{$m}-21') TO ('{$y}-{$m}-26');";
        $ny = $y;
        $nm = $m + 1; 
        if ($m >= 12) { 
            $ny += 1;
            $nm = '01';
        }
        $nm = sprintf("%02d", $nm);
        $arr[] = "CREATE TABLE ${table_name}_{$y}{$m}_06 PARTITION OF $table_name FOR VALUES FROM ('{$y}-{$m}-26') TO ('{$ny}-{$nm}-01');";
    }

    foreach ($arr as $r) { 
        file_put_contents($to_write_file, $r. "\n", FILE_APPEND);
        
    }
}

create_table_partition('account_changes');
